/**
 * Created by woziji00226 on 2021-12-30 08:36:34.
 */
(function () {
    EventUtils.addEventListener(ClientWorld, ClientWorld.EVENT_INITED, Callback.New(() => {
        Game.player.data.w26_LockpickLoad = 0;
        stage.on(EventObject.KEY_DOWN, this, (e: EventObject) => {
            W26_GUI_lock.keyCode = e.keyCode;
        });
        stage.on(EventObject.KEY_UP, this, (e: EventObject) => {
            W26_GUI_lock.keyCode = null;
        });
    }, this));
})();

class W26_GUI_lock extends GUI_15001 {
    static PLUGIN_GUI_LOCK: number = 15001;
    static COMPLETED: string;
    static keyCode: number;

    backOpacity: number;
    _timer: number;
    _turnTimer: number;
    _posTimer: number;
    _turnPosition: number;
    _turnRange: number;
    _openRange: any[];
    _broke: boolean;
    _isBlocked: boolean;
    _isBlockedPik: boolean;
    _gametesting: boolean;
    _skill: number;
    _strength: number;
    _hasItem: number;
    pxd_lp_posit_repeat: number = 30;
    LockpickLoad: number;

    isOpend: boolean = false;

    constructor() {
        super();
        W26_GUI_lock.keyCode = null;
        this.background.on(EventObject.MOUSE_MOVE, this, this.moveLeftStick);
        stage.on(EventObject.KEY_UP, this, this.onKeyDown);
        os.add_ENTERFRAME(this.update, this);
        this.once(GameSprite.ON_DISPOSE, this, () => {
            os.remove_ENTERFRAME(this.update, this);
            stage.off(EventObject.KEY_UP, this, this.onKeyDown);
            this.background.offAll();
        })
        this.alpha = 0;
    }

    showLeftStick() {
        this._leftStickImage.visible = false;
        this._leftStickImage2.visible = false;
        if (Game.player.data.w26_LockpickLoad > 0) {
            this._leftStickImage.visible = true;
        }
        else {

        }
    }

    showLeftBrokeStick() {
        this._leftStickImage.visible = false;
        this._leftStickImage2.visible = true;
    }

    showLeftFullStick() {
        this._leftStickImage.visible = true;
        this._leftStickImage2.visible = false;
    }

    showResetLock() {
        this.label3.visible = true;
    }

    showUnResetLock() {
        this.label3.visible = false;
    }

    start() {
        W26_GUI_lock.keyCode = null;
        this.isOpend = true;
        this._broke = true;
        this.backOpacity = 0;
        this._timer = 0;
        this._turnTimer = 0;
        this._posTimer = 0;
        this._turnPosition = 49;
        this._turnRange = 0;
        this._openRange = [];
        this.LockpickLoad = 100;

        this._isBlocked = false;
        this._isBlockedPik = false;
        this._gametesting = false;
        this._skill = Game.player.data.W26_lockSkill;
        this.setOpenPosition();
        if (Game.player.data.w26_LockpickLoad > 0) {
            this.showUnResetLock();
        }
        else {
            this.showResetLock();
        }
        //初始化棒子
        this.showLeftStick();
        this.refreshLockaid();

        var g = this.background.graphics;
        g.clear();
        g.drawRect(0, 0, this.background.width, this.background.height, "#000000");

        //this.reset();

        Tween.to(this, { "alpha": 1 }, 300, Ease.linearOut, Callback.New(() => {
            this.isOpend = false;
            this._broke = false;
        }, this));
    }

    toJD(hd: number): number {
        return 180 / Math.PI * hd;
    }

    toHD(jd: number): number {
        return Math.PI / 180 * jd;
    }

    moveLeftStick() {
        if (!this._broke && !this._isBlockedPik && !this.isOpend && Game.player.data.w26_LockpickLoad > 0) {
            var x = this.background.mouseX - this._leftStick.x;
            var y = this.background.mouseY - this._leftStick.y;
            this._leftStick.rotation = (this.toJD(Math.atan2(y, x)) + 270) % 360;
            this.setLockPosition();
            this.positSound();
        }
    }

    onKeyDown(e: EventObject) {
        if (this.isOpend) return;
        if (e.keyCode == WorldData.w26_quitLockGUI) {
            this.event(W26_GUI_lock.COMPLETED, false);
            this.quit();
        }
        else if (e.keyCode == WorldData.w26_resetLock) {
            this.reset();
        }

    }

    quit() {
        this.isOpend = true;
        Tween.to(this, { "alpha": 0 }, 600, Ease.linearOut, Callback.New(() => {
            GameUI.dispose(W26_GUI_lock.PLUGIN_GUI_LOCK);
            W26_GUI_lock.keyCode = null;
        }, this));
    }

    reset() {
        if (!this.label3.visible) return;
        if (Game.player.data.W26_lockaidGunCount <= 0) {
            return;
        }
        if (Game.player.data.w26_LockpickLoad > 0) {
            return;
        }
        W26_GUI_lock.keyCode = null;
        Game.player.data.W26_lockaidGunCount -= 1;
        this.refreshLockaid();
        Game.player.data.w26_LockpickLoad = 100;
        this.showUnResetLock();
        this.showLeftFullStick();
        this._broke = false;
        this.moveLeftStick();
    }

    refreshLockaid() {
        this.lockaidGunCount.text = Game.player.data.W26_lockaidGunCount.toString();
    }

    update() {
        if (this.isOpend) return;
        if (!W26_GUI_lock.keyCode || this._broke || this._isBlocked) {
            if (this._rightStick.rotation > 0) {
                this._rightStick.rotation -= 2;
                if (this._rightStick.rotation < 0) {
                    this._rightStick.rotation = 0;
                }
            }
        }
        else {
            if (WorldData.w26_turnKey.indexOf(W26_GUI_lock.keyCode) != -1 && !this._broke && Game.player.data.w26_LockpickLoad > 0) {//AD
                if (this._rightStick.rotation < 90) {
                    this._rightStick.rotation += 1;
                    this.getTurnPosition();
                    this.pickLock();
                    this.turnSound();
                }
            }
        }
        if (this._timer == 60) {
            if (!this._isBlocked) {

            } else {
                this._broke = false;
                this._timer = 0;
                this._isBlocked = false;
                this.moveLeftStick();
            }
        }
        if (this._isBlockedPik && !this._isBlocked) {
            if (this._timer > 10) this._isBlockedPik = false;
        }
        this._timer++;
    }

    setStrength(strength) {
        this._strength = strength;
    }

    range_clamp(value, min, max): number {
        var result = value;
        if (value > max) result = max;
        else if (value < min) result = min;
        //debugger;
        return result;
    }

    Math_randomInt(value): number {
        return Math.floor(Math.random() * (value + 1))
    }

    setOpenPosition() {
        var skill = this._skill;
        var strength = this._strength;

        strength = strength / 100;
        skill = skill / strength;

        var range = 0;

        if (skill >= 100) {
            range = 23;
        } else if (skill >= 90) {
            range = 21;
        } else if (skill >= 80) {
            range = 19;
        } else if (skill >= 70) {
            range = 17;
        } else if (skill >= 60) {
            range = 15;
        } else if (skill >= 50) {
            range = 13;
        } else if (skill >= 40) {
            range = 11;
        } else if (skill >= 30) {
            range = 9;
        } else if (skill >= 20) {
            range = 7;
        } else if (skill >= 10) {
            range = 5;
        } else if (skill >= 1) {
            range = 3;
        }

        range = this.range_clamp(range, 3, 99);
        var max_pos = 101;
        var position = this.Math_randomInt(max_pos) - (range / 2 - 0.5);

        var mid = [];
        for (var i = position; i < position + range; i++) {
            mid.push(i);
        }

        var down = [];
        for (var i = position; i < position + (range / 2 - 0.5); i++) {
            down.push(i);
        }

        var up = [];
        for (var i = position + range - 1; i > position + (range / 2 - 0.5); i--) {
            up.push(i);
        }

        var newlist = [];
        for (var i = 0; i < (range / 2 - 0.5); i++) {
            var d = down[i];
            var u = up[i];
            newlist.push([d, u]);
        }

        mid = mid[range / 2 - 0.5];
        this._openRange = newlist;
        this._openRange.push(mid);

        //DASDADQ2asdawdasdadwadsadwdastrace(this._openRange);
    }

    pickLock() {
        var open = false;
        var fail = 0;

        var skill = this._skill;
        var strength = this._strength;

        strength = strength / 100;
        skill = (skill) / strength;


        var bonus = this._strength - this._skill;
        bonus = bonus > 0 ? bonus : 0;

        var value = skill < 100 ? (101 - skill) / 10 : 1;
        value = value + bonus;
        var openRange = this._openRange;
        var mid = openRange[openRange.length - 1];
        var rate = openRange.length / 100;
        var x = Math.round(this._turnRange * rate);
        x = this.range_clamp(x, 0, openRange.length - 1);
        //debugger
        if (this._turnRange >= 90) {
            return this.openLock();
        }

        if (openRange[x][0] == this._turnPosition || openRange[x][1] == this._turnPosition) {
            return this.blockLock(value);
        }

        for (var i = 0; i < openRange.length; i++) {
            if (openRange[i][0] == this._turnPosition || openRange[i][1] == this._turnPosition || mid == this._turnPosition) {
                return;
            }

        }
        this.blockLock(value);
    }

    checkLock() {
        if (Game.player.data.w26_LockpickLoad <= 0) {
            this.breakLockpick();
        }
    }

    openLock() {
        this._broke = true;
        this._timer = -60;
        this.openSound();
        this.event(W26_GUI_lock.COMPLETED, true);
        this.quit();

    }

    breakLockpick() {
        this._broke = true;
        this._isBlocked = false;
        this._timer = 0;
        this.showLeftBrokeStick();
        if (Game.player.data.W26_lockaidGunCount < 0) {
            this.showUnResetLock();
        }
        else {
            this.showResetLock();
        }
        this.breakSound();
    }

    blockLock(value: number) {
        //trace("blockloac", value);
        this._broke = true;
        this._isBlocked = true;
        this._isBlockedPik = true;
        this._timer = 56;
        Game.player.data.w26_LockpickLoad -= Math.floor(value);
        if (Game.player.data.w26_LockpickLoad < 0) Game.player.data.w26_LockpickLoad = 0;
        //trace(Game.player.data.w26_LockpickLoad);
        this.failSound();
        this.checkLock();
    }

    setLockPosition() {
        this._turnPosition = Math.round(this._leftStick.rotation / 360 * 100);
    }

    getTurnPosition() {
        this._turnRange = this._rightStick.rotation
    }

    openSound() {
        GameAudio.playSE(WorldData.w26_lock_sound_open, 1);
    }

    failSound() {
        GameAudio.playSE(WorldData.w26_lock_sound_fail);
    }

    breakSound() {
        GameAudio.playSE(WorldData.w26_lock_sound_break);
    }

    positSound() {
        if (this._posTimer == 0) {
            var sound = WorldData.w26_lock_sound_position[this.Math_randomInt(WorldData.w26_lock_sound_position.length)]
            GameAudio.playSE(sound, Math.floor(((Math.random() * 30) + 50) / 100));
            this._posTimer++;
        } else {
            this._posTimer++;
        }
        if (this._posTimer >= 8) {
            this._posTimer = 0;
        }
    }

    turnSound() {
        if (this._turnTimer == 0) {
            var sound = WorldData.w26_lock_sound_turn[this.Math_randomInt(WorldData.w26_lock_sound_turn.length)]
            GameAudio.playSE(sound, Math.floor(((Math.random() * 30) + 50) / 100));
            this._turnTimer++;
        } else {
            this._turnTimer++;
        }
        if (this._turnTimer >= 8) {
            this._turnTimer = 0;
        }
    }
}

module CustomGameNumber {
    /**
     * 自定义游戏数值
     * @param trigger 触发器，可能为空
     * @param p 自定义数值参数 
     */
    export function f1(trigger: CommandTrigger, p: CustomGameNumberParams_1): number {
        if (p.w26_lockType == 0) {
            return Game.player.data.W26_lockaidGunCount;
        }
        else {
            return Game.player.data.W26_lockSkill;
        }
    }
}

module CommandExecute {
    /**
     * 自定义命令执行 1表示对应1号命令
     * @param commandPage 事件页
     * @param cmd 当前的事件命令
     * @param trigger 触发器
     * @param triggerPlayer 触发器对应的玩家
     * @param playerInput 玩家输入值，用于暂停执行该触发器事件并等待玩家输入后获得的值，执行完该函数后会被清空
     * @param p 自定义命令参数 1表示对应1号命令的参数
     */
    export function customCommand_15001(commandPage: CommandPage, cmd: Command, trigger: CommandTrigger, triggerPlayer: ClientPlayer, playerInput: any[], p: CustomCommandParams_15001): void {
        trigger.pause = true;
        trigger.offset(1);
        var guiLock = GameUI.show(W26_GUI_lock.PLUGIN_GUI_LOCK) as W26_GUI_lock;
        guiLock.setStrength(p.strength);
        guiLock.start();
        guiLock.once(W26_GUI_lock.COMPLETED, this, (t: CommandTrigger, id: number, res: boolean) => {
            Game.player.variable.setSwitch(id, res ? 1 : 0);
            CommandPage.executeEvent(t, []);
        }, [trigger, p.resSwitch]);

    }

    export function customCommand_15002(commandPage: CommandPage, cmd: Command, trigger: CommandTrigger, triggerPlayer: ClientPlayer, playerInput: any[], p: CustomCommandParams_15002): void {
        if (0 == p.lockType) {
            Game.player.data.W26_lockaidGunCount = p.useVar ? Game.player.variable.getVariable(p.lockCount1) : p.lockCount;
        }
        else {
            Game.player.data.W26_lockSkill = p.useVar1 ? Game.player.variable.getVariable(p.lockSikll1) : p.lockSkill;
        }
    }
}



